package com.heima.kafka.stream;

import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;

@Configuration
public class KafkaStreamListener {

    @Bean
    public KStream<String, String> kStream(StreamsBuilder streamsBuilder) {
        //订阅指定的topic中的消息，进行处理,获取到KStream
        KStream<String, String> kStream = streamsBuilder.stream("heima-stream-topic1");

        //使用KStream执行流式计算的逻辑
        kStream.flatMapValues(new ValueMapper<String, Iterable<String>>() {

                    //对消息进行处理，返回value
                    @Override
                    public Iterable<String> apply(String value) {
                        //value:  "hello kafka" -> "hello","kafka"
                        return Arrays.asList(value.split(" "));
                    }
                })
                //进行分组，一个单词分成一组
                .groupBy((key, value) -> value)
                //指定事件时间的窗口，用多长时间进行分段
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                //计算单词出现的数量
                .count()
                //计算完成，再转为流
                .toStream()
                .map((key, value) -> {
                    System.out.println("key:" + key + "::" + "value:" + value);
                    return new KeyValue<>(key.key().toString(), value.toString());
                })
                .to("heima-stream-result1");

        return kStream;
    }
}
